const { Collection } = require('mongodb')
const mongoUtil = require('./mongo_util')
const collectionName = 'goods'
var ObjectID = require('mongodb').ObjectId

function creatgoodlist(data, callback) {
	mongoUtil.getCollection(collectionName).then((collection) => {
		collection.insertOne(data, function (err, res) {
			callback(err, res)
		})
	})
}

function deletegoodlist(data, callback) {
	const ids = data._id.map((item) => {
		const id = ObjectID(item)
		return id
	})
	mongoUtil.getCollection(collectionName).then((collection) => {
		collection.deleteMany({ _id: { $in: ids } }, function (err, res) {
			callback(err, res)
		})
	})
}

function updategoodlist(data, callback) {
	const { _id, ...newvalue } = data
	const xx = {
		_id: ObjectID(_id),
	}
	var updateStr = { $set: newvalue }
	mongoUtil.getCollection(collectionName).then((collection) => {
		collection.updateOne(xx, updateStr, (err, res) => {
			callback(err, res)
		})
	})
}

function getgoodlists(obj, callback) {
	console.log('mongoUtil.getCollection=', obj)
	var { page, size, type } = obj
	if (type) {
		type = { $and: type }
	}
	console.log(type)
	const mmp = mongoUtil.getCollection(collectionName)
	console.log('mmp=', mmp)
	mmp.then((collection) => {
		async function xx() {
			const total = await collection.find(type).count()
			console.log('getUser result=', total)
			collection
				.find(type)
				.skip(size*(page-1))
				.limit(size * 1)
				.toArray(function (err, result) {
					// 返回集合中所有数据

					const data = {
						total,
						data: result,
					}
					if (result.length) {
						callback(null, data)
					} else {
						callback(err, data)
					}
				})
		}
		xx()
	})
}
function searchgoods(obj, callback) {
     const {keyword,page,size}=obj
	const arr=[{title: eval('/' + keyword + '/')},{autho: eval('/' + keyword + '/')}]
	const mmp = mongoUtil.getCollection(collectionName)
	console.log('mmp=', mmp)
	mmp.then((collection) => {
		async function xx() {
			const total = await collection.find({$or:arr}).count()
			console.log('getUser result=', total)
			collection
				.find({$or:arr}).skip(size*(page-1))
				.limit(size * page)
				.toArray(function (err, result) {
					// 返回集合中所有数据

					const data = {
						total,
						data: result,
					}
					if (result.length) {
						callback(null, data)
					} else {
						callback(err, data)
					}
				})
		}
		xx()
	})
}
function getdeatel(goodsid, callback) {
	const mmp = mongoUtil.getCollection(collectionName)
	console.log('id', goodsid)
	mmp.then((collection) => {
		collection
			.find({ _id: ObjectID(goodsid) })
			.toArray(function (err, result) {
				// 返回集合中所有数据
				console.log('getUser result=', result)
				if (result) {
					callback(null, result)
				} else {
					callback(err, null)
				}
			})
	})
}
module.exports = {
	creatgoodlist,
	deletegoodlist,
	updategoodlist,
	getgoodlists,
	getdeatel,
	searchgoods
}
